<template>
  <div class="box">
    <header class="header">
       <van-nav-bar
        title="登录"
        left-arrow
        @click-left="$router.back()"
      />
    </header>
    <div class="content">
      <van-field
        v-model="loginname"
        center
        clearable
        placeholder="账户名/手机号/邮箱"
      >
      </van-field>
      <van-field
        v-model="password"
        center
        clearable
        placeholder="密码"
      >
      </van-field>
      <van-button @click="login" :disabled="flag" round class="btn" block color="#ff6666">登录</van-button>
      <router-link to="/register/step1">立即注册</router-link>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { NavBar, Field, Button, Toast } from 'vant'
import { dologin } from './../../api/user'
Vue.use(NavBar)
Vue.use(Field)
Vue.use(Button)
export default {
  data () {
    return {
      loginname: '1881300781',
      password: 'Ty2103'
    }
  },
  computed: {
    flag () {
      return !/^\S*(?=\S{6,})(?=\S*\d)(?=\S*[A-Z])(?=\S*[a-z])\S*$/.test(this.password) || this.loginname.length < 3
    }
  },
  methods: {
    login () {
      dologin({
        loginname: this.loginname,
        password: this.password
      }).then(res => {
        if (res.data.code === '10010') {
          Toast('登录账户不存在')
        } else if (res.data.code === '10011') {
          Toast('密码错误')
        } else {
          console.log(res.data)
          Toast('登录成功')
          // 保存信息到本地
          // token 后端校验用户登录的凭证
          // userid 知道是那一个用户
          localStorage.setItem('isLogin', true) // 前端校验登录的方式
          localStorage.setItem('token', res.data.data.token)
          localStorage.setItem('userid', res.data.data.userid)
          // 修改状态管理器 --- 唯一修改状态的方式就是显示的提交mutations
          this.$store.commit('changeLoginState', true)
          this.$router.back()
        }
      })
    }
  }
}
</script>
